/**
 * Title: HomeActivity.java
 * Description:
 * Copyright: Copyright (c) 2008
 * Company:深圳彩讯科技有限公司
 * Author 罗旭东 (hi@luoxudong.com)
 * Date 2013-11-24 上午11:30:54
 * Version 1.0
 */
package com.luoxudong.phonenumber.ui.activities;

import java.util.ArrayList;
import java.util.List;

import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;

import com.luoxudong.phonenumber.R;
import com.luoxudong.phonenumber.logic.db.model.PhoneNumber;
import com.luoxudong.phonenumber.ui.adapters.PhoneNumberListAdapter;
import com.luoxudong.phonenumber.ui.common.listener.OnItemClickAvoidForceListener;
import com.luoxudong.phonenumber.ui.widgets.pulltorefresh.PullToRefreshBase;
import com.luoxudong.phonenumber.ui.widgets.pulltorefresh.PullToRefreshBase.OnRefreshListener2;
import com.luoxudong.phonenumber.ui.widgets.pulltorefresh.PullToRefreshBase.State;
import com.luoxudong.phonenumber.ui.widgets.pulltorefresh.PullToRefreshListView;
import com.luoxudong.phonenumber.ui.widgets.scrollbanner.BannerItem;
import com.luoxudong.phonenumber.ui.widgets.scrollbanner.ScrollBanner;
import com.luoxudong.phonenumber.ui.widgets.titlebar.TitleBarView;

/** 
 * ClassName: HomeActivity
 * Description:首页tab
 * Create by 罗旭东
 * Date 2013-11-24 上午11:30:54
 */
public class HomeActivity extends AbsSubActivity{
	private TitleBarView titleBarView = null;
	private ScrollBanner scrollBanner = null;
	private PullToRefreshListView numberListView = null;
	private PhoneNumberListAdapter adapter = null;
	private List<PhoneNumber> phoneNumbers = null;
	private LoadDataTask loadDataTask = null;
	
	@Override
	protected int getContentViewLayoutResId() {
		return R.layout.home_layout;
	}

	@Override
	protected void onCreateFindView(Bundle savedInstanceState) {
		titleBarView = (TitleBarView)findViewById(R.id.title_bar);
		scrollBanner = (ScrollBanner)findViewById(R.id.sb_ads);
		numberListView = (PullToRefreshListView)findViewById(R.id.plv_home_number_list);
		
		titleBarView.setTitle(R.string.home);
	}

	@Override
	protected void onCreateAddListener(Bundle savedInstanceState) {
		numberListView.setOnItemClickListener(onItemClickListener);
	}

	@Override
	protected void onCreateInitData(Bundle savedInstanceState) {
		adapter = new PhoneNumberListAdapter(this, phoneNumbers);
		List<BannerItem> bannerItems = new ArrayList<BannerItem>();
		BannerItem bannerItem = null;
		
		bannerItem = new BannerItem();
		bannerItem.setResId(R.drawable.banner_image_default);
		bannerItems.add(bannerItem);
		
		bannerItem = new BannerItem();
		bannerItem.setResId(R.drawable.banner_image_default);
		bannerItems.add(bannerItem);
		
		bannerItem = new BannerItem();
		bannerItem.setResId(R.drawable.banner_image_default);
		bannerItems.add(bannerItem);
		scrollBanner.setImages(bannerItems);
		
		numberListView.setAdapter(adapter);
		
		numberListView.setOnRefreshListener(new OnRefreshListener2<ListView>() {
			@Override
			public void onPullDownToRefresh(PullToRefreshBase<ListView> refreshView) {
				pullDownToRefresh();
			}

			@Override
			public void onPullUpToRefresh(PullToRefreshBase<ListView> refreshView) {		
				pullUpToRefresh();
			}
		});
		
		onRefreshing();
	}

	@Override
	protected void onCreateTaskLoadData() {
		
	}

	@Override
	protected void onCreateTaskAddView() {
		
	}

	@Override
	protected void refreshUI(Object obj) {
		if (adapter != null)
		{
			adapter.notifyDataSetChanged();
			numberListView.invalidate();
		}
	}
	
	/**
	 * 自动下拉刷新界面
	 * 
	 */
	public void onRefreshing()
	{
		numberListView.onRefreshComplete();
		numberListView.setRefreshing();
		numberListView.setState(State.MANUAL_REFRESHING, true);
		pullDownToRefresh();
	}
	
	/**
	 * 下拉刷新
	 * 
	 */
	private void pullDownToRefresh()
	{
		if (loadDataTask != null)
		{
			loadDataTask.cancel(true);
		}
		loadDataTask = new LoadDataTask(0);
		loadDataTask.execute();
	}
	
	/**
	 * 上拉显示更多
	 * 
	 * @return void
	 */
	private void pullUpToRefresh()
	{
		if (!numberListView.isRefreshing())
		{
			if (loadDataTask != null)
			{
				loadDataTask.cancel(true);
			}
			loadDataTask = new LoadDataTask(1);
			loadDataTask.execute();
		}
	}
	
	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_BACK && event.getAction() == KeyEvent.ACTION_DOWN)
		{
			exitApp();
			return true;
			
		}
		return super.onKeyDown(keyCode, event);
	}
	
	public void onBackPressed() {
		exitApp();
	};
	
	/**
	 * 删除已经存在的文件
	 * @param newDatas
	 */
	public List<PhoneNumber> removeRepeated(List<PhoneNumber> newDatas)
	{
		List<PhoneNumber> currentDatas = adapter.getList();
		List<PhoneNumber> tempList = new ArrayList<PhoneNumber>();
		
		if (currentDatas != null && newDatas != null)
		{
			for (PhoneNumber t : newDatas)
			{
				for (PhoneNumber item : currentDatas)
				{
					if (t.getPhoneNumber() != null && item.getPhoneNumber().equals(t.getPhoneNumber()))//存在相同的
					{
						tempList.add(item);
						break;
					}
				}
			}
			
			//currentDatas.removeAll(tempList);
		}
		
		return newDatas;
	}
	
	private List<PhoneNumber> loadTestData()
	{
		List<PhoneNumber> phoneNumbers = new ArrayList<PhoneNumber>();
    	PhoneNumber phoneNumber = null;
    	
    	phoneNumber = new PhoneNumber();
    	phoneNumber.setAreaId(110000);
    	phoneNumber.setCallPrice(40.4f);
    	phoneNumber.setPhoneBrandId(1);
    	phoneNumber.setPhoneNumber("16834534123");
    	phoneNumber.setTelOperatorId(0);
    	phoneNumber.setTotalPrice(300.0f);
    	phoneNumbers.add(phoneNumber);
    	
    	phoneNumber = new PhoneNumber();
    	phoneNumber.setAreaId(220500);
    	phoneNumber.setCallPrice(10.4f);
    	phoneNumber.setPhoneBrandId(1);
    	phoneNumber.setPhoneNumber("15678901234");
    	phoneNumber.setTelOperatorId(1);
    	phoneNumber.setTotalPrice(200.0f);
    	phoneNumbers.add(phoneNumber);
    	
    	phoneNumber = new PhoneNumber();
    	phoneNumber.setAreaId(110003);
    	phoneNumber.setCallPrice(30.4f);
    	phoneNumber.setPhoneBrandId(1);
    	phoneNumber.setPhoneNumber("13545678901");
    	phoneNumber.setTelOperatorId(2);
    	phoneNumber.setTotalPrice(140.0f);
    	phoneNumbers.add(phoneNumber);
    	
    	phoneNumber = new PhoneNumber();
    	phoneNumber.setAreaId(433100);
    	phoneNumber.setCallPrice(50.4f);
    	phoneNumber.setPhoneBrandId(1);
    	phoneNumber.setPhoneNumber("13612345678");
    	phoneNumber.setTelOperatorId(1);
    	phoneNumber.setTotalPrice(600.0f);
    	phoneNumbers.add(phoneNumber);
    	
    	return phoneNumbers;
	}
	
	private OnItemClickAvoidForceListener onItemClickListener = new OnItemClickAvoidForceListener() {
		
		@Override
		public void onItemClickAvoidForce(AdapterView<?> parent, View view, int position, long id) {
			PhoneNumber item = adapter.getItem((int)parent.getAdapter().getItemId(position));
			if (item == null)
			{
				return;
			}
			
			Intent intent = new Intent(HomeActivity.this, PhoneNumberDetailActivity.class);
			intent.putExtra("phoneNumber", item);
			startActivity(intent);
		}
	};
	
	class LoadDataTask extends AsyncTask<Void, Void, List<PhoneNumber>> {
    	private int flag = 0;//0:下拉刷新,1:上拉获取数据
		
    	public LoadDataTask(int flag)
    	{
    		this.flag = flag;
    	}
    	
		@Override
		protected void onPreExecute() {
			
			super.onPreExecute();
		}
		
        @Override
        protected List<PhoneNumber> doInBackground(Void... params) {
        	try {
				Thread.sleep(2000);
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
        	
    		return loadTestData();
        }

        @Override
        protected void onPostExecute(List<PhoneNumber> result) {
        	appendData(result);
        	numberListView.onRefreshComplete();
            cancel(false);
            sendMessage(obtainMessage(MSG_REFRESH_UI, null));
        }
        
        private void appendData(List<PhoneNumber> result)
        {
        	if (adapter != null)
    		{
    			adapter.appendToBottomList(removeRepeated(result));
    		}
        }
        
    }
}
